package com.example.xm.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/upfile")
public class FileController {
    //   获得自定义的props.path  yaml里的
    @Value("${upfile.photoPath}")
    String upFolder;
    @Value("${upfile2.photoPath2}")
    String upFolder2;
    /**
     * 图片上传
     */
    @RequestMapping("/files")
    String upFiler(@RequestPart MultipartFile file) throws IOException {
        //指定上传的路径
        String path = upFolder;
        String path2 = upFolder2;

        //获取当前文件的文件名 比如: 1.jpg
        String originName = file.getOriginalFilename();
        /**
         * 新的文件名
         * UUID.randomUUID().toString()
         *  获得UUID编号
         * originName.substring(originName.lastIndexOf("."))
         *  获得文件后缀名
         * 结果 88cb5b7e-034e-4eec~8b0e-e2cb23622886.jpg
         */
        String filename = UUID.randomUUID().toString() + originName.substring(originName.lastIndexOf("."));
        //将文件上传到指定位置  位置path
        file.transferTo(new File(path + filename));
        //将文件上传到指定位置  位置path2
        //file.transferTo(new File(path2 + filename));

        Path sourcePath = Paths.get(path + filename);
        Path destPath = Paths.get(path2 + filename);
        Files.copy(sourcePath, destPath); // 复制文件到另一个文件夹

        System.out.println(path+ filename + "      " + path2 + filename);

        return filename;
    }
}